/**
 * 智能压缩页面逻辑
 * 提供图片压缩功能，支持质量、尺寸、格式调整
 */

const { imageProcessor } = require('../../utils/image-processor');

Page({
  data: {
    // 图片数据
    originalImage: '',
    originalSize: 0,
    compressedImage: '',
    compressedSize: 0,
    savingRatio: 0,
    
    // 压缩参数
    quality: 80,
    maxWidth: 1920,
    maxHeight: 1080,
    format: 'jpg',
    removeExif: true,
    progressive: false,
    
    // 格式选项
    formats: [
      { name: 'JPG', value: 'jpg' },
      { name: 'PNG', value: 'png' },
      { name: 'WebP', value: 'webp' }
    ],
    
    // 批量处理
    batchMode: false,
    batchImages: [],
    
    // UI状态
    loading: false,
    showProgress: false,
    progressTitle: '',
    progressPercent: 0,
    progressText: ''
  },

  /**
   * 生命周期函数 - 页面加载
   */
  onLoad(options) {
    this.setData({
      batchMode: options.batch === 'true'
    });
    
    // 监听全局事件
    this.setupEventListeners();
  },

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // 监听图片选择事件
    wx.onAppShow(() => {
      const app = getApp();
      if (app.globalData.selectedImages) {
        this.handleSelectedImages(app.globalData.selectedImages);
        app.globalData.selectedImages = null;
      }
    });
  },

  /**
   * 选择图片
   */
  chooseImage() {
    const count = this.data.batchMode ? 9 : 1;
    
    wx.chooseImage({
      count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (this.data.batchMode) {
          this.addToBatch(res.tempFilePaths);
        } else {
          this.loadImage(res.tempFilePaths[0]);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 加载并显示图片
   */
  async loadImage(imagePath) {
    try {
      this.setData({ loading: true });
      
      const imageInfo = await imageProcessor.loadImage(imagePath);
      const fileSize = await imageProcessor.getFileSize(imagePath);
      
      this.setData({
        originalImage: imagePath,
        originalSize: fileSize,
        compressedImage: '',
        compressedSize: 0,
        savingRatio: 0
      });
      
      // 自动压缩预览
      this.compressPreview();
      
    } catch (error) {
      wx.showToast({
        title: '加载图片失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 压缩预览
   */
  async compressPreview() {
    if (!this.data.originalImage) return;
    
    try {
      this.setData({ loading: true });
      
      const compressedPath = await imageProcessor.compressImage({
        imagePath: this.data.originalImage,
        quality: this.data.quality,
        maxWidth: this.data.maxWidth,
        maxHeight: this.data.maxHeight,
        format: this.data.format,
        removeExif: this.data.removeExif
      });
      
      const compressedSize = await imageProcessor.getFileSize(compressedPath);
      const savingRatio = Math.round(
        ((this.data.originalSize - compressedSize) / this.data.originalSize) * 100
      );
      
      this.setData({
        compressedImage: compressedPath,
        compressedSize,
        savingRatio
      });
      
    } catch (error) {
      wx.showToast({
        title: '压缩预览失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 保存压缩图片
   */
  async saveImage() {
    if (!this.data.compressedImage) {
      wx.showToast({
        title: '请先生成压缩图片',
        icon: 'none'
      });
      return;
    }

    try {
      // 检查权限
      await this.checkSavePermission();
      
      // 保存图片
      await this.saveToAlbum(this.data.compressedImage);
      
      // 记录处理历史
      this.saveToHistory();
      
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
      
    } catch (error) {
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  /**
   * 检查保存权限
   */
  async checkSavePermission() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: resolve,
              fail: () => {
                wx.showModal({
                  title: '权限提示',
                  content: '需要相册权限才能保存图片',
                  showCancel: false
                });
                reject(new Error('权限不足'));
              }
            });
          } else {
            resolve();
          }
        }
      });
    });
  },

  /**
   * 保存到相册
   */
  saveToAlbum(filePath) {
    return new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath,
        success: resolve,
        fail: reject
      });
    });
  },

  /**
   * 保存处理历史
   */
  saveToHistory() {
    const history = {
      id: Date.now(),
      originalImage: this.data.originalImage,
      compressedImage: this.data.compressedImage,
      originalSize: this.data.originalSize,
      compressedSize: this.data.compressedSize,
      savingRatio: this.data.savingRatio,
      operation: 'compress',
      timestamp: new Date().toISOString()
    };
    
    const app = getApp();
    app.addToHistory(history);
  },

  /**
   * 事件处理 - 质量滑块变化
   */
  onQualityChange(e) {
    this.setData({ quality: e.detail.value });
    this.compressPreview();
  },

  /**
   * 事件处理 - 最大宽度变化
   */
  onMaxWidthChange(e) {
    const value = parseInt(e.detail.value) || 1920;
    this.setData({ maxWidth: value });
    this.compressPreview();
  },

  /**
   * 事件处理 - 最大高度变化
   */
  onMaxHeightChange(e) {
    const value = parseInt(e.detail.value) || 1080;
    this.setData({ maxHeight: value });
    this.compressPreview();
  },

  /**
   * 事件处理 - 格式变化
   */
  onFormatChange(e) {
    this.setData({ format: e.detail.value });
    this.compressPreview();
  },

  /**
   * 添加到批量处理
   */
  addToBatch() {
    if (!this.data.originalImage) return;
    
    const batchImages = [...this.data.batchImages];
    
    if (batchImages.length >= 9) {
      wx.showToast({
        title: '最多支持9张图片',
        icon: 'none'
      });
      return;
    }
    
    batchImages.push({
      id: Date.now(),
      path: this.data.originalImage,
      size: this.data.originalSize
    });
    
    this.setData({ batchImages });
    
    wx.showToast({
      title: '已添加',
      icon: 'success'
    });
  },

  /**
   * 清空批量
   */
  clearBatch() {
    this.setData({ batchImages: [] });
  },

  /**
   * 重置所有设置
   */
  resetAll() {
    this.setData({
      originalImage: '',
      originalSize: 0,
      compressedImage: '',
      compressedSize: 0,
      savingRatio: 0,
      quality: 80,
      maxWidth: 1920,
      maxHeight: 1080,
      format: 'jpg',
      batchImages: []
    });
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const { src } = e.currentTarget.dataset;
    wx.previewImage({
      urls: [src]
    });
  }
});